<?php
/*
 Plugin Name: Wandhi_ImagePaster
 Plugin URI: https://www.wandhi.com
 Description: 粘贴图片上传新浪
 Author: wandhi
 Version: 1.0.0
 Author URI: https://www.wandhi.com/
 */

if (!defined("Wandhi_ImagePaster")) {
    $Wandhi_ImagePaster = str_replace(realpath(dirname(__FILE__) . '/..'), "", dirname(__FILE__));
    $Wandhi_ImagePaster = substr($Wandhi_ImagePaster, 1);
    define("Wandhi_ImagePaster", $Wandhi_ImagePaster);
}

define("Wandhi_ImagePaster_URL", WP_CONTENT_URL . "/plugins/" . Wandhi_ImagePaster . "/");

add_action("init", "Wandhi_ImagePaster_Init");
add_action('admin_head', 'Wandhi_ImagePaster_AdminHeader');
add_action('init', 'Wandhi_ImagePaster_AddButton');
add_action('wp_ajax_imagepaste_action', 'Wandhi_ImagePaster_AjaxCallback');
/**
 * 初始化
 */
function Wandhi_ImagePaster_Init()
{
    if (is_admin()) {
        wp_enqueue_script("jquery");
    }
}

/**
 * 添加库
 */
function Wandhi_ImagePaster_AdminHeader()
{
    if (!current_user_can('edit_posts') && !current_user_can('edit_pages')) {
        return;
    }
    echo '<script type="text/javascript" src="' . Wandhi_ImagePaster_URL . '/js/' . 'jquery.paste_image_reader.js" ></script>';
}

/**
 * 添加提示按钮
 *
 * @param $buttons
 *
 * @return mixed
 */
function Wandhi_ImagePaster_Button($buttons)
{
    array_push($buttons, "separator", "tinyimagepaste");

    return $buttons;
}

function Wandhi_ImagePaster_AddButton()
{
    if (!current_user_can('edit_posts') && !current_user_can('edit_pages')) {
        return;
    }

    if (get_user_option('rich_editing') == 'true') {
        add_filter("mce_external_plugins", "Wandhi_ImagePaster_Tinymce_plugin");
        add_filter('mce_buttons', 'Wandhi_ImagePaster_Button');
    }
}

function Wandhi_ImagePaster_Tinymce_plugin($plugin_array)
{
    $plugin_array['tinyimagepaste'] = plugins_url() . '/' . Wandhi_ImagePaster . '/tinymce/' . 'editor_plugin.js';

    return $plugin_array;
}

function Wandhi_ImagePaster_AjaxCallback()
{
    $response   = array("error" => '');
    $uploadinfo = wp_upload_dir();
    $uploadPath = $uploadinfo['path'];
    $imgdata    = $_REQUEST['imgdata'];
    list($data, $image) = explode(';', $imgdata);
    list($field, $type) = explode(':', $data);
    list($encoding, $content) = explode(',', $image);

    $wandhi = new Wandhi_ImagePaster();

    $extension = $wandhi->getImageInfo($imgdata['tmp_name']);// 'png';//暂时都处理为png
    $filename  = md5($imgdata) . '.' . $extension;

    $wandhi->SaveToLocal($uploadPath, $filename, $content);
    $res = $wandhi->UpToHidove();
    if ($res == "-1") {
        $response['error'] = "上传失败";
    } else {
        $response['url'] = $res;
    }
    echo json_encode($response);
    die();
}

class Wandhi_ImagePaster
{
    public $file;

    public function SaveToLocal($uploadPath, $filename, $content)
    {
        $this->file = $uploadPath . '/' . $filename;
        file_put_contents($this->file, base64_decode($content));
    }

    public function UpToSina()
    {
        $ch   = curl_init();
        $data = array('file' => '@' . $this->file);
        //兼容5.0-5.6版本的curl
        if (class_exists('\CURLFile')) {
            $data['file'] = new \CURLFile(realpath($this->file));
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        curl_setopt($ch, CURLOPT_URL, 'https://apis.yum6.cn/api/5bd44dc94bcfc?token=f07b711396f9a05bc7129c4507fb65c5');
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        try {
            $res = curl_exec($ch);
            if (!$res) return "-1";
            $res_obj = json_decode($res, true);
            if (array_key_exists("data", $res_obj)) {
                if (array_key_exists("url", $res_obj['data'])) {
                    unlink($this->file);
                    return $res_obj['data']['url'];
                }
            }
        } catch (Exception $e) {
            unlink($this->file);
            return "-1";
        }

        return "-1";
    }

    public function UpToHidove($referer = 'https://www.baidu.com', $headers = array('Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'))
    {
        $post = [
            'image' => '@' . $this->file,
            'type'  => 'ali'
        ];
        $url  = 'https://api.abcyun.co/api/picbed/index/token/5d8f31cf6a8ab';
        // 创建一个新 cURL 资源
        $curl = curl_init();
        //兼容5.0-5.6版本的curl
        if (class_exists('\CURLFile')) {
            $data['file'] = new \CURLFile(realpath($this->file));
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        // 设置URL和相应的选项
        // 需要获取的 URL 地址
        curl_setopt($curl, CURLOPT_URL, $url);
        #启用时会将头文件的信息作为数据流输出。
        curl_setopt($curl, CURLOPT_HEADER, false);
        #设置头部信息
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        #在尝试连接时等待的秒数。设置为 0，则无限等待。
        // curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
        #允许 cURL 函数执行的最长秒数。
        // curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        #设置请求信息
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        #设置referer
        curl_setopt($curl, CURLOPT_REFERER, $referer);
        #关闭ssl
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        #TRUE 将 curl_exec获取的信息以字符串返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // 抓取 URL 并把它传递给浏览器
        try {
            $res = curl_exec($curl);
            if (!$res) return "-1";
            $res_obj = json_decode($res, true);
            if (array_key_exists("url", $res_obj)) {
                if (array_key_exists("ali", $res_obj['data'])) {
                    unlink($this->file);
                    return $res_obj['url']['ali'];
                }
            }
        } catch (Exception $e) {
            unlink($this->file);
            return "-1";
        }

        return "-1";
    }

    public function getImageInfo($fileName)
    {
        $data = getimagesize($fileName);
        switch ($data[2]) {
            case 1:
                return [
                    'type' => 'gif',
                    'mime' => $data['mime']
                ];
            case 2:
                return [
                    'type' => 'jpg',
                    'mime' => $data['mime']
                ];
            case 3:
                return [
                    'type' => 'png',
                    'mime' => $data['mime']
                ];
            case 6:
                return [
                    'type' => 'bmp',
                    'mime' => $data['mime']
                ];
            case 17:
                return [
                    'type' => 'ico',
                    'mime' => $data['mime']
                ];
            default:
                return [
                    'type' => 'Unown type',
                    'mime' => $data['mime']
                ];
        }
    }
}